<!--========公告管理页面============-->
<script setup>
import {onMounted, ref, watch} from 'vue'
import http from "@/request/Http.js";
import {ElMessage} from "element-plus";

//公告数据
const announcements = ref([])

//当前页码，每页大小，总记录数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const dialogVisible = ref(false)
const dialogTitle = ref('发布公告')
const form = ref({id: null, title: '', content: '', createdAt: '', status: 1})

const detailVisible = ref(false)
const detail = ref({})

const filter = ref({title: ''})

// 重置
const onFilterReset = () => {
  filter.value = {title: ''}
  // 重置页码
  currentPage.value = 1
  //刷新
  getAnnouncements()
}

// 打开新增/编辑公告弹窗
function openDialog(row) {
  if (row) {
    dialogTitle.value = '编辑公告'
    form.value = {...row}
  } else {
    dialogTitle.value = '发布公告'
    form.value = {title: '', content: ''}
  }
  dialogVisible.value = true
}

//获取公告列表
const getAnnouncements = async () => {
  const params = new URLSearchParams()
  params.append('currentPage', currentPage.value)
  params.append('pageSize', pageSize.value)
  if (filter.value.title) {
    params.append('title', filter.value.title)
  }
  const data = await http.post('/admin/getAnnouncement?' + params.toString())
  console.log("获取公告列表成功:", data)
  if (data.code === 200) {
    announcements.value = data.data.records
    total.value = data.data.total
  }
}

// 标题查询
const onFilterSearch = () => {
  // 重置页码
  currentPage.value = 1
  getAnnouncements()
}

//发布/修改公告
const addAnnouncement = async () => {

  if (form.value.id) {
    //编辑公告
    const data = await http.post('/admin/updateAnnouncement', form.value)
    if (data.code === 200) {
      //刷新列表
      await getAnnouncements()
      ElMessage.success("公告修改成功")
    } else {
      ElMessage.error(data.msg)
    }
  } else {
    //新增公告
    if (form.value.title && form.value.content) {
      //关闭弹窗
      dialogVisible.value = false

      const noticeData = {
        title: form.value.title,
        content: form.value.content
      }

      const data = await http.post('/admin/addAnnouncement', noticeData)
      console.log(data.data)
      if (data.code === 200) {
        //刷新列表
        await getAnnouncements()
        ElMessage.success('公告发布成功')
      } else {
        ElMessage.error(data.msg)
        console.log(data.msg)
      }
    } else {
      ElMessage.error('标题和内容不能为空')
    }
  }
}

//启用/禁用公告
const toggleStatus = async (row) => {
  // 切换状态
  row.status = row.status === 1 ? 0 : 1;

  const params = new URLSearchParams();
  params.append('id', row.id);
  params.append('status', row.status);

  const data = await http.post('/admin/updateAnnouncementStatus', params);
  console.log(data);
  if (data.code === 200) {
    //刷新列表
    await getAnnouncements();
    ElMessage.success("公告状态更新成功");
  } else {
    ElMessage.error(data.msg);
  }
}

//删除公告
const deleteAnnouncement = async (row) => {

  const params = new URLSearchParams();
  params.append('id', row.id);

  //发送删除请求
  const data = await http.post('/admin/deleteAnnouncement', params);
  if (data.code === 200) {
    //刷新列表
    await getAnnouncements()
    ElMessage.success("公告删除成功")
  } else {
    console.log(data.msg)
    ElMessage.error(data.msg)
  }
}

//查看公告详情
const viewAnnouncement = (row) => {
  detail.value = {...row};  // 将当前行数据赋值给detail
  detailVisible.value = true;  // 显示详情弹窗
}

// 处理每页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getAnnouncements()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getAnnouncements()
}

// 监听页码变化
watch(currentPage, () => {
  getAnnouncements()
})

// 监听每页大小变化
watch(pageSize, () => {
  getAnnouncements()
})

// 页面加载时获取公告列表
onMounted(() => {
  getAnnouncements()
})

</script>

<template>
  <div class="announcement-manage">
    <!-- 主区域 -->
    <el-card>
      <!-- 条件查询区域 -->
      <div class="header">
        <!-- 条件查询区域 -->
        <el-form
            :inline="true"
            class="filter-form"
            @submit.prevent
        >
          <el-form-item label="公告标题">
            <el-input
                v-model="filter.title"
                clearable
                placeholder="请输入公告标题"
                style="width:200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="onFilterSearch">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="onFilterReset">重置</el-button>
          </el-form-item>
        </el-form>
        <el-button class="ml" type="primary" @click="openDialog()">发布公告</el-button>
      </div>

      <!--公告列表-->
      <el-table :data="announcements" border style="width: 100%">
        <el-table-column label="标题" min-width="180" prop="title"/>
        <el-table-column label="内容" min-width="300" prop="content"/>
        <el-table-column label="发布时间" prop="createdAt" width="180"/>
        <el-table-column label="状态" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status===1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <!--操作列表-->
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button size="small" @click="viewAnnouncement(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="openDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteAnnouncement(scope.row)">删除</el-button>
            <el-button :type="scope.row.status === 1 ? 'warning' : 'success'" size="small"
                       @click="toggleStatus(scope.row)">
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>

      </el-table>

      <!-- 分页组件 -->
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30]"
          :total="total"
          background
          class="pagination"
          layout="prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 公告新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="form" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="form.title"/>
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="form.content" :rows="5" type="textarea"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addAnnouncement">保存</el-button>
      </template>
    </el-dialog>

    <!-- 公告详情弹窗 -->
    <el-dialog v-model="detailVisible" :show-close="true" title="公告详情" width="500px">
      <div>
        <h3>{{ detail.title }}</h3>
        <p style="color: #888; font-size: 13px;">&nbsp; 发布时间：{{ detail.createdAt }}</p>
        <div style="margin-top: 16px;">{{ detail.content }}</div>
      </div>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<style scoped>
.announcement-manage {
  padding: 24px;
}

.header {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-start;
}

.pagination {
  margin-top: 16px;
  text-align: right;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-pagination) {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.08);
  padding: 8px 20px;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 4px;
  margin: 0 2px;
  transition: background 0.2s, color 0.2s;
}

:deep(.el-pagination .el-pager li.active) {
  background: linear-gradient(90deg, #409EFF 0%, #66b1ff 100%);
  color: #fff;
  font-weight: bold;
}

:deep(.el-pagination .el-pager li:hover) {
  background: #e6f0ff;
  color: #409EFF;
}

.filter-form {
  margin-bottom: 18px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px 16px;
}

.filter-form .el-form-item {
  margin-bottom: 0 !important;
}

.filter-form .el-button {
  min-width: 70px;
}

</style>